package com.feng.leetcode;

import java.util.*;

/**
 * @author feng
 * @decrLition
 * @date 2022/11/30:32
 */
public class L1620 {
    public static int[] bestCoordinate(int[][] towers, int radius) {
        if (towers.length == 1) {
            if (towers[0][2] == 0) {
                return new int[]{0, 0};
            }
            return new int[]{towers[0][0], towers[0][1]};
        }
        Map<int[], Integer> orign = new HashMap<>();
        int minx = Integer.MAX_VALUE;
        int maxx = Integer.MIN_VALUE;
        int miny = Integer.MAX_VALUE;
        int maxy = Integer.MIN_VALUE;
        for (int i = 0; i < towers.length; i++) {
            int x = towers[i][0];
            int y = towers[i][1];
            minx = Math.min(minx, x);
            maxx = Math.max(maxx, x);
            miny = Math.min(y, miny);
            maxy = Math.max(y, maxy);
            orign.put(new int[]{x, y}, towers[i][2]);
        }
        ArrayList<Temp> result = new ArrayList<>();
        for (int i = minx; i <= maxx; i++) {
            for (int j = miny; j <= maxy; j++) {
                Set<Map.Entry<int[], Integer>> entries = orign.entrySet();
                int sumQi = 0;
                for (Map.Entry<int[], Integer> entry : entries) {
                    int[] key = entry.getKey();
                    Integer value = entry.getValue();
                    int sum = (key[0] - i) * (key[0] - i) + (key[1] - j) * (key[1] - j);
                    double sqrt = Math.sqrt(sum);
                    if (sqrt <= radius) {
                        int qi = (int) Math.floor(value / (1 + sqrt));
                        sumQi += qi;
                    }
                }
                result.add(new Temp(i, j, sumQi));
            }
        }
        Collections.sort(result, (o1, o2) -> {
            Temp a = (Temp) o1;
            Temp b = (Temp) o2;
            if (a.value != b.value) {
                return b.value - a.value;
            } else {
                if (a.x != b.x) {
                    return a.x - b.x;
                } else {
                    return a.y - b.y;
                }
            }
        });
        Temp temp = result.get(0);
        return new int[]{temp.x, temp.y};
    }

    public static class Temp {
        int x;
        int y;
        int value;

        public Temp(int x, int y, int value) {
            this.x = x;
            this.y = y;
            this.value = value;
        }
    }
}
